{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-u7xRR3DeFXz"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "oed1Dh9SeIlD"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DzkEdu7YxUOM"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://ai.google.dev/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers\"><img src=\"https://ai.google.dev/static/site-assets/images/docs/notebook-site-button.png\" height=\"32\" width=\"32\" />View on ai.google.dev</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/google/generative-ai-docs/blob/main/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb\"\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://kaggle.com/kernels/welcome?src=https://github.com/google/generative-ai-docs/blob/main/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb\"><img src=\"https://www.kaggle.com/static/images/logos/kaggle-logo-transparent-300.png\" height=\"32\" width=\"70\"/>Run in Kaggle</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/google/generative-ai-docs/main/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb\"><img src=\"https://ai.google.dev/images/cloud-icon.svg\" width=\"40\" />Open in Vertex AI</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/google/generative-ai-docs/blob/main/site/en/gemma/docs/embeddinggemma/fine-tuning-embeddinggemma-with-sentence-transformers.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Txf-DZy2yCJ5"
      },
      "source": [
        "# Fine-tune EmbeddingGemma\n",
        "\n",
        "Fine-tuning helps close the gap between a model's general-purpose understanding and the specialized, high-performance accuracy that your application requires. Since no single model is perfect for every task, fine-tuning adapts it to your specific domain.\n",
        "\n",
        "Imagine your company, \"Shibuya Financial\" offers various complex financial products like investment trusts, NISA accounts (a tax-advantaged savings account), and home loans. Your customer support team uses an internal knowledge base to quickly find answers to customer questions.\n",
        "\n",
        "## Setup\n",
        "\n",
        "Before starting this tutorial, complete the following steps:\n",
        "\n",
        "* Get access to EmbeddingGemma by logging into [Hugging Face](https://huggingface.co/google/embeddinggemma-300M) and selecting **Acknowledge license** for a Gemma model.\n",
        "* Generate a Hugging Face [Access Token](https://huggingface.co/docs/hub/en/security-tokens#how-to-manage-user-access-token) and use it to login from Colab.\n",
        "\n",
        "This notebook will run on either CPU or GPU."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rZdmGmJq0NJX"
      },
      "source": [
        "### Install Python packages\n",
        "\n",
        "Install the libraries required for running the EmbeddingGemma model and generating embeddings. Sentence Transformers is a Python framework for text and image embeddings. For more information, see the [Sentence Transformers](https://www.sbert.net/) documentation."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "zhVtxMWG0TP7"
      },
      "outputs": [],
      "source": [
        "!pip install -U sentence-transformers git+https://github.com/huggingface/transformers@v4.56.0-Embedding-Gemma-preview"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "O3ttIyfSA0Lj"
      },
      "source": [
        "After you have accepted the license, you need a valid Hugging Face Token to access the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Ev43EyYQ0Gj8"
      },
      "outputs": [],
      "source": [
        "# Login into Hugging Face Hub\n",
        "from huggingface_hub import login\n",
        "login()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XyzbOscl0ack"
      },
      "source": [
        "### Load Model\n",
        "\n",
        "Use the `sentence-transformers` libraries to create an instance of a model class with EmbeddingGemma."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "E6w85SW70gph"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Device: cuda:0\n",
            "SentenceTransformer(\n",
            "  (0): Transformer({'max_seq_length': 2048, 'do_lower_case': False, 'architecture': 'Gemma3TextModel'})\n",
            "  (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})\n",
            "  (2): Dense({'in_features': 768, 'out_features': 3072, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})\n",
            "  (3): Dense({'in_features': 3072, 'out_features': 768, 'bias': False, 'activation_function': 'torch.nn.modules.linear.Identity'})\n",
            "  (4): Normalize()\n",
            ")\n",
            "Total number of parameters in the model: 307581696\n"
          ]
        }
      ],
      "source": [
        "import torch\n",
        "from sentence_transformers import SentenceTransformer\n",
        "\n",
        "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
        "\n",
        "model_id = \"google/embeddinggemma-300M\"\n",
        "model = SentenceTransformer(model_id).to(device=device)\n",
        "\n",
        "print(f\"Device: {model.device}\")\n",
        "print(model)\n",
        "print(\"Total number of parameters in the model:\", sum([p.numel() for _, p in model.named_parameters()]))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WJA4tSu-0s4Y"
      },
      "source": [
        "## Prepare the Fine-Tuning Dataset\n",
        "\n",
        "This is the most crucial part. You need to create a dataset that teaches the model what \"similar\" means in your specific context. This data is often structured as triplets: (anchor, positive, negative)\n",
        "\n",
        "- Anchor: The original query or sentence.\n",
        "- Positive: A sentence that is semantically very similar or identical to the anchor.\n",
        "- Negative: A sentence that is on a related topic but semantically distinct.\n",
        "\n",
        "In this example, we only prepared 3 triplets, but for a real application, you would need a much larger dataset to perform well."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "CIkQ7fyR0vSR"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Dataset({\n",
            "    features: ['anchor', 'positive', 'negative'],\n",
            "    num_rows: 3\n",
            "})\n"
          ]
        }
      ],
      "source": [
        "from datasets import Dataset\n",
        "\n",
        "dataset = [\n",
        "    [\"How do I open a NISA account?\", \"What is the procedure for starting a new tax-free investment account?\", \"I want to check the balance of my regular savings account.\"],\n",
        "    [\"Are there fees for making an early repayment on a home loan?\", \"If I pay back my house loan early, will there be any costs?\", \"What is the management fee for this investment trust?\"],\n",
        "    [\"What is the coverage for medical insurance?\", \"Tell me about the benefits of the health insurance plan.\", \"What is the cancellation policy for my life insurance?\"],\n",
        "]\n",
        "\n",
        "# Convert the list-based dataset into a list of dictionaries.\n",
        "data_as_dicts = [ {\"anchor\": row[0], \"positive\": row[1], \"negative\": row[2]} for row in dataset ]\n",
        "\n",
        "# Create a Hugging Face `Dataset` object from the list of dictionaries.\n",
        "train_dataset = Dataset.from_list(data_as_dicts)\n",
        "print(train_dataset)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "31jCsHUy0zwP"
      },
      "source": [
        "## Before Fine-Tuning\n",
        "\n",
        "A search for \"tax-free investment\" might have given the following results, with similarity scores:\n",
        "\n",
        "1. Document: Opening a NISA account (Score: 0.51)\n",
        "2. Document: Opening a Regular Saving Account (Score: 0.50) <- *Similar score, potentially confusing*\n",
        "3. Document: Home Loan Application Guide (Score: 0.44)\n",
        "\n",
        "> Note: To generate optimal embeddings with EmbeddingGemma, you should add an \"instructional prompt\" or \"task\" to the beginning of your input text. You will use `STS` for sentence similarity. For details on all available EmbeddingGemma prompts, see the [model card](http://ai.google.dev/gemma/docs/embeddinggemma/model_card#prompt_instructions)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eM06urFi1Br_"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Document:  Opening a NISA Account -> 🤖 Score:  0.51571906\n",
            "Document:  Opening a Regular Savings Account -> 🤖 Score:  0.5035889\n",
            "Document:  Home Loan Application Guide -> 🤖 Score:  0.4406476\n"
          ]
        }
      ],
      "source": [
        "task_name = \"STS\"\n",
        "\n",
        "def get_scores(query, documents):\n",
        "  # Calculate embeddings by calling model.encode()\n",
        "  query_embeddings = model.encode(query, prompt_name=task_name)\n",
        "  doc_embeddings = model.encode(documents, prompt_name=task_name)\n",
        "\n",
        "  # Calculate the embedding similarities\n",
        "  similarities = model.similarity(query_embeddings, doc_embeddings)\n",
        "\n",
        "  for idx, doc in enumerate(documents):\n",
        "    print(\"Document: \", doc, \"-> 🤖 Score: \", similarities.numpy()[0][idx])\n",
        "\n",
        "query = \"I want to start a tax-free installment investment, what should I do?\"\n",
        "documents = [\"Opening a NISA Account\", \"Opening a Regular Savings Account\", \"Home Loan Application Guide\"]\n",
        "\n",
        "get_scores(query, documents)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LfzasM-41Yb3"
      },
      "source": [
        "## Training\n",
        "\n",
        "Using a framework like `sentence-transformers` in Python, the base model gradually learns the subtle distinctions in your financial vocabulary."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8OX8XPUL1d2V"
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "\n",
              "    <table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              " <tr style=\"text-align: left;\">\n",
              "      <th>Step</th>\n",
              "      <th>Training Loss</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <td>3</td>\n",
              "      <td>0.048300</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>6</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>9</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>12</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <td>15</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table><p>"
            ],
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Step 3 finished. Running evaluation:\n",
            "Document:  Opening a NISA Account -> 🤖 Score:  0.6459116\n",
            "Document:  Opening a Regular Savings Account -> 🤖 Score:  0.42690125\n",
            "Document:  Home Loan Application Guide -> 🤖 Score:  0.40419024\n",
            "Step 6 finished. Running evaluation:\n",
            "Document:  Opening a NISA Account -> 🤖 Score:  0.68530923\n",
            "Document:  Opening a Regular Savings Account -> 🤖 Score:  0.3611964\n",
            "Document:  Home Loan Application Guide -> 🤖 Score:  0.40812016\n",
            "Step 9 finished. Running evaluation:\n",
            "Document:  Opening a NISA Account -> 🤖 Score:  0.7168733\n",
            "Document:  Opening a Regular Savings Account -> 🤖 Score:  0.3449782\n",
            "Document:  Home Loan Application Guide -> 🤖 Score:  0.44477722\n",
            "Step 12 finished. Running evaluation:\n",
            "Document:  Opening a NISA Account -> 🤖 Score:  0.73008573\n",
            "Document:  Opening a Regular Savings Account -> 🤖 Score:  0.34124148\n",
            "Document:  Home Loan Application Guide -> 🤖 Score:  0.4676212\n",
            "Step 15 finished. Running evaluation:\n",
            "Document:  Opening a NISA Account -> 🤖 Score:  0.73378766\n",
            "Document:  Opening a Regular Savings Account -> 🤖 Score:  0.34055778\n",
            "Document:  Home Loan Application Guide -> 🤖 Score:  0.47503752\n",
            "Step 15 finished. Running evaluation:\n",
            "Document:  Opening a NISA Account -> 🤖 Score:  0.73378766\n",
            "Document:  Opening a Regular Savings Account -> 🤖 Score:  0.34055778\n",
            "Document:  Home Loan Application Guide -> 🤖 Score:  0.47503752\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "TrainOutput(global_step=15, training_loss=0.009651267528511198, metrics={'train_runtime': 195.3004, 'train_samples_per_second': 0.077, 'train_steps_per_second': 0.077, 'total_flos': 0.0, 'train_loss': 0.009651267528511198, 'epoch': 5.0})"
            ]
          },
          "execution_count": 8,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from sentence_transformers import SentenceTransformerTrainer, SentenceTransformerTrainingArguments\n",
        "from sentence_transformers.losses import MultipleNegativesRankingLoss\n",
        "from transformers import TrainerCallback\n",
        "\n",
        "loss = MultipleNegativesRankingLoss(model)\n",
        "\n",
        "args = SentenceTransformerTrainingArguments(\n",
        "    # Required parameter:\n",
        "    output_dir=\"my-embedding-gemma\",\n",
        "    # Optional training parameters:\n",
        "    prompts=model.prompts[task_name],    # use model's prompt to train\n",
        "    num_train_epochs=5,\n",
        "    per_device_train_batch_size=1,\n",
        "    learning_rate=2e-5,\n",
        "    warmup_ratio=0.1,\n",
        "    # Optional tracking/debugging parameters:\n",
        "    logging_steps=train_dataset.num_rows,\n",
        "    report_to=\"none\",\n",
        ")\n",
        "\n",
        "class MyCallback(TrainerCallback):\n",
        "    \"A callback that evaluates the model at the end of eopch\"\n",
        "    def __init__(self, evaluate):\n",
        "        self.evaluate = evaluate # evaluate function\n",
        "\n",
        "    def on_log(self, args, state, control, **kwargs):\n",
        "        # Evaluate the model using text generation\n",
        "        print(f\"Step {state.global_step} finished. Running evaluation:\")\n",
        "        self.evaluate()\n",
        "\n",
        "def evaluate():\n",
        "  get_scores(query, documents)\n",
        "\n",
        "trainer = SentenceTransformerTrainer(\n",
        "    model=model,\n",
        "    args=args,\n",
        "    train_dataset=train_dataset,\n",
        "    loss=loss,\n",
        "    callbacks=[MyCallback(evaluate)]\n",
        ")\n",
        "trainer.train()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8rcmxOME1kCg"
      },
      "source": [
        "## After Fine-Tuning\n",
        "\n",
        "The same search now yields much clearer results:\n",
        "\n",
        "1. Document: Opening a NISA account (Score: 0.73) <- *Much more confident*\n",
        "2. Document: Opening a Regular Saving Account (Score: 0.34) <- *Clearly less relevant*\n",
        "3. Document: Home Loan Application Guide (Score: 0.47)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Zdt-ve0x1mD3"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Document:  Opening a NISA Account -> 🤖 Score:  0.73378766\n",
            "Document:  Opening a Regular Savings Account -> 🤖 Score:  0.34055778\n",
            "Document:  Home Loan Application Guide -> 🤖 Score:  0.47503752\n"
          ]
        }
      ],
      "source": [
        "get_scores(query, documents)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x0bSI_PUQBw7"
      },
      "source": [
        "To upload your model to the Hugging Face Hub, you can use the `push_to_hub` method from the Sentence Transformers library.\n",
        "\n",
        "Uploading your model makes it easy to access for inference directly from the Hub, share with others, and version your work. Once uploaded, anyone can load your model with a single line of code, simply by referencing its unique model ID `<username>/my-embedding-gemma`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4wioFS7oQP6I"
      },
      "outputs": [],
      "source": [
        "# Push to Hub\n",
        "model.push_to_hub(\"my-embedding-gemma\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y8te9XtU1r3m"
      },
      "source": [
        "## Summary and next steps\n",
        "\n",
        "You have now learned how to adapt an EmbeddingGemma model for a specific domain by fine-tuning it with the Sentence Transformers library.\n",
        "\n",
        "Explore what more you can do with EmbeddingGemma:\n",
        "\n",
        "* [Training Overview](https://sbert.net/docs/sentence_transformer/training_overview.html) in Sentence Transformers Documentation\n",
        "* [Generate embeddings with Sentence Transformers](https://ai.google.dev/gemma/docs/embeddinggemma/inference-embeddinggemma-with-sentence-transformers)\n",
        "* [Simple RAG example](https://github.com/google-gemini/gemma-cookbook/blob/main/Gemma/%5BGemma_3%5DRAG_with_EmbeddingGemma.ipynb) in the Gemma Cookbook\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "fine-tuning-embeddinggemma-with-sentence-transformers.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
